package com.hz.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 退出登录
 */
@Component
public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 从这里拿到token 然后把这个token注销
        String token = httpServletRequest.getHeader("userToken");

        // 去redis删除token
        stringRedisTemplate.delete(token);

        MassageJson massageJson = new MassageJson();
        massageJson.setCode(004);
        massageJson.setMsg("退出成功!");

        httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(massageJson));
    }
}
